package com.itheima.service.impl;

import com.itheima.common.utils.POIUtils;
import com.itheima.mapper.OrderSettingMapper;
import com.itheima.pojo.OrderSetting;
import com.itheima.pojo.vo.OrderSettingVO;
import com.itheima.service.OrderSettingService;
import lombok.extern.slf4j.Slf4j;
import org.apache.poi.ss.usermodel.BorderStyle;
import org.apache.poi.xssf.usermodel.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.time.LocalDate;
import java.time.temporal.TemporalAdjusters;
import java.util.Arrays;
import java.util.List;
import java.util.Objects;
import java.util.stream.Collectors;

@Service
@Slf4j
public class OrderSettingServiceImpl implements OrderSettingService {
    @Autowired
    private OrderSettingMapper orderSettingMapper;

    /**
     * 查询预约设置
     *
     * @param month
     * @return
     */
    @Override
    public List<OrderSettingVO> getOrderSettingByMonth(String month) {
        log.info("查询预约设置，月份信息为{}", month);
        LocalDate monthDate = LocalDate.of(Integer.parseInt(month.split("-")[0]), Integer.parseInt(month.split("-")[1]), 1);
        LocalDate lastDay = monthDate.withDayOfMonth(monthDate.lengthOfMonth());
        List<OrderSetting> orderSettings = orderSettingMapper.selectByField(monthDate, lastDay);
        log.info("{}", lastDay);
        log.info("查询结果为{}", orderSettings);
        return orderSettings
                .stream()
                // 调试方法
                //.peek(orderSetting -> System.out.println(orderSetting.getOrderDate()))
                .map(
                        orderSetting -> new OrderSettingVO(
                                orderSetting.getOrderDate().getDayOfMonth(),
                                orderSetting.getNumber(),
                                orderSetting.getReservations()
                        )
                ).collect(Collectors.toList());
    }

    /**
     * 修改预约设置
     *
     * @param orderSetting
     * @return
     */
    @Override
    public Boolean editNumberByDate(OrderSetting orderSetting) {
        log.info("修改预约设置，预约设置信息为{}", orderSetting);
        Integer result;
        OrderSetting oldOrderSetting = orderSettingMapper.selectByDay(orderSetting.getOrderDate());
        try {
            // TODO需要注意不能低于已预约人数

            // 先查询是否存在
            if (oldOrderSetting == null) {
                // 不存在直接插入新数据
                result = orderSettingMapper.insert(orderSetting);
            } else {
                // 存在则修改
                result = orderSettingMapper.updateByDate(orderSetting);
            }

            return result >= 0;
        } catch (Exception e) {
            log.error("修改预约设置失败，错误信息为{}", e.getMessage());
            return false;
        }
    }

    /**
     * 文件下载
     */
    @Override
    public void download(String uri, HttpServletResponse response) {
        // 1.查询数据
        LocalDate firstDay = LocalDate.now().with(TemporalAdjusters.firstDayOfMonth());
        LocalDate lastDay = LocalDate.now().with(TemporalAdjusters.lastDayOfMonth());
        List<OrderSetting> orderSettings = orderSettingMapper.selectByField(firstDay, lastDay);

        // 2.文件操作
        InputStream in = this.getClass().getClassLoader().getResourceAsStream("templates/" + uri);
        try {
            XSSFWorkbook xssfWorkbook = new XSSFWorkbook(Objects.requireNonNull(in));
            XSSFSheet sheetAtFirst = xssfWorkbook.getSheetAt(0);
            // 样式
            XSSFCellStyle defaultStyle = xssfWorkbook.createCellStyle();
            defaultStyle.setBorderTop(BorderStyle.THIN);
            defaultStyle.setBorderBottom(BorderStyle.THIN);
            defaultStyle.setBorderLeft(BorderStyle.THIN);
            defaultStyle.setBorderRight(BorderStyle.THIN);
            // 赋值
            for (int i = 0; i < orderSettings.size(); i++) {
                OrderSetting orderSetting = orderSettings.get(i);

                XSSFRow row = sheetAtFirst.createRow(i + 1);
                XSSFCell date = row.createCell(0);
                date.setCellStyle(defaultStyle);
                XSSFCell number = row.createCell(1);
                number.setCellStyle(defaultStyle);

                date.setCellValue(orderSetting.getOrderDate().toString());
                number.setCellValue(orderSetting.getNumber());
            }

            // 设置响应头
            response.setContentType("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet"); // 设置 MIME 类型为 Excel 文件
            response.setHeader("Content-Disposition", "attachment; filename=ordersetting_template.xlsx"); // 设置文件名
            OutputStream os = response.getOutputStream();
            xssfWorkbook.write(os);

            xssfWorkbook.close();
            in.close();
        } catch (IOException e) {
            log.info("文件下载失败，错误信息为{}", e.getMessage());
        }
    }

    /**
     * 文件上传
     *
     * @param excelFile
     */
    @Override
    public void upload(MultipartFile excelFile) {
        POIUtils.getWorkBook(excelFile).getSheetAt(0);
        try {
            List<String[]> Rows = POIUtils.readExcel(excelFile);
            Rows.forEach(row -> {
                System.out.println(Arrays.toString(row));
                orderSettingMapper.updateByDate(new OrderSetting(
                        LocalDate.parse(row[0]), (int) Double.parseDouble(row[1])
                ));
            });
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
    }
}
